import { useLoginStore } from '@/stores/login'
import axios, { type Method } from 'axios'

const service = axios.create({
  baseURL: 'https://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 20 * 1000,
})

// 返回的类型
interface ServiceResponse<T> {
  code: string
  msg: string
  result: T
}

export const request = <T>(url: string, method: Method = 'GET', submitData?: object) => {
  return service<T, ServiceResponse<T>>({
    url: url,
    method: method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData,
  })
}

// 添加请求拦截器
service.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const store = useLoginStore()
    if (store.profile?.token) {
      config.headers.Authorization = `Bearer ${store.profile.token}`
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  },
)

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    return res.data
  },
  (err) => {
    return Promise.reject(err)
  },
)
